package co.baiku.boot.action;

import co.baiku.boot.common.spring.SpringContext;
import co.baiku.boot.common.tools.JsonTools;
import co.baiku.boot.common.tools.ServletTools;
import co.baiku.boot.common.tools.StringTools;
import co.baiku.boot.common.tools.XmlTools;
import co.baiku.boot.common.validate.Validation;
import co.baiku.boot.config.AlipayConfig;
import co.baiku.boot.pay.Alipay;
import co.baiku.boot.type.AlipayMessageType;
import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

public class AlipayExecutor {
    private Logger log = LoggerFactory.getLogger(AlipayExecutor.class);
    private Alipay alipay;
    private final Map<String, AlipayActionExecutor> executorMap = new HashMap<>();

    public AlipayExecutor(Alipay alipay) {
        this.alipay = alipay;
        Map<String, AlipayActionExecutor> executors = SpringContext.getBeansOfType(AlipayActionExecutor.class);
        executors.forEach((k, v) -> {
            AlipayMessageType alipayMessageType = v.msgType();
            executorMap.put(alipayMessageType.getMessageType(), v);
        });
    }

    public String gateway(HttpServletRequest request) throws AlipayApiException {
        Map<String, String> params = ServletTools.convertRequestParamsToMap(request);
        if (log.isDebugEnabled()) {
            log.debug("[AlipayExecutor] uri:{},query:{}", request.getQueryString(), JsonTools.beanToJson(params));
        }
        return gateway(params);
    }

    public String gateway(Map<String, String> params) throws AlipayApiException {
        return proccessBizContent(doExecutor(params));
    }

    private String proccessBizContent(String bizContent) throws AlipayApiException {
        AlipayConfig alipayConfig = alipay.getAlipayConfig();
        return alipay.encryptAndSign(bizContent, alipayConfig.getAlipayPublicKey(),
                alipayConfig.getPrivateKey(), StringTools.UTF8.name(), false, true, alipayConfig.getSignType());
    }

    private String doExecutor(Map<String, String> params) {
        //获取服务信息
        String service = params.get("service");
        if (StringUtils.isEmpty(service)) {
            throw Validation.error("无法取得服务名");
        }

        //获取内容信息
        String bizContentJson = params.get("biz_content");
        if (StringUtils.isEmpty(bizContentJson)) {
            throw Validation.error("无法取得业务内容信息");
        }

        //将XML转化成json对象
        Map<String, String> bizContent = null;
        try {
            bizContent = XmlTools.xmlToMap(bizContentJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (bizContent != null) {
            // 1.获取消息类型信息
            //传递brandId 物祥云充电宝业务id传递
            bizContent.put("brandId", params.get("brandId"));
            String msgType = bizContent.get("MsgType");
            if (StringUtils.isEmpty(msgType)) {
                throw Validation.error("无法取得消息类型");
            }
            AlipayActionExecutor executor = executorMap.get(msgType);
            if (executor != null) {
                return executor.execute(alipay, bizContent);
            }
            return "";
        } else {
            throw Validation.error("bizContent 解析失败");
        }
    }

}
